﻿@model Gateway.Console.Models.AnalyticsModel

@{
    ViewBag.Title = "Application Analytics";
}

<h2>Application Analytics</h2>

@if (ViewBag.RdfeAuthorizationFailure)
{
    <p>
        <strong>
            An error has occurred attempting to obtain authorization for access to Microsoft Azure Management API.<br />
        </strong>
    </p>
    <p>Details:</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorCode</p>
    <p class="field-validation-error">@ViewBag.AuthorizationErrorDescription</p>
    <br />
    <p>
        <strong>
            Before this application can deploy analytics components to Microsoft Azure, it must be authorized for access to the Microsoft Azure Management API.<br />
            Click the link below to begin the authorizing access.
        </strong>
    </p>
    <br />
    @Html.ActionLink("Start Authorizing Access", "Index", "Security");
}
else
{
    using (Html.BeginForm())
    {
        @Html.HiddenFor(model => model.Id)
        <div class="checkbox">
            @Html.CheckBoxFor(model => model.EnableAnalytics, new { @class = "enable-analytics" }).Disable(() => Model.Disabled) Enable Application Analytics
        </div>
        @Html.ValidationSummary(true)

        <div class="analytics-entry">
            <div class="form-group">
                @Html.LabelFor(model => model.AvailableClusters)
                @Html.DropDownListFor(model => model.ClusterName,
                    Model.AvailableClusters.Select(cluster => new SelectListItem { Value = cluster.Item1, Text = cluster.Item2 }),
                    new { @class = "form-control cluster-use" })
            </div>
            <div class="form-group create-cluster" style="display: none;">
                @Html.LabelFor(model => model.ClusterNameToCreate, true)
                @Html.TextBoxFor(model => model.ClusterNameToCreate, new { @class = "form-control create-cluster" })
                @Html.ValidationMessageFor(model => model.ClusterNameToCreate)
            </div>
            <div class="form-group create-cluster" style="display: none;">
                @Html.LabelFor(model => model.ClusterNodeCount, true)
                @Html.TextBoxFor(model => model.ClusterNodeCount, new { @class = "form-control create-cluster" })
                @Html.ValidationMessageFor(model => model.ClusterNodeCount)
            </div>
            <div class="form-group create-cluster" style="display: none;">
                @Html.LabelFor(model => model.ClusterUserName, true)
                @Html.TextBoxFor(model => model.ClusterUserName, new { @class = "form-control create-cluster" })
                @Html.ValidationMessageFor(model => model.ClusterUserName)
            </div>
            <div class="form-group create-cluster" style="display: none;">
                @Html.LabelFor(model => model.ClusterPassword, true)
                @Html.PasswordFor(model => model.ClusterPassword, new { @class = "form-control create-cluster" })
                @Html.ValidationMessageFor(model => model.ClusterPassword)
            </div>
        </div>
        <div class="form-actions no-color">
            @Html.Submit("create", "Apply", new { @class = "btn btn-default" }).Disable(() => Model.Disabled)
            @if (Model.Id != 0)
            {
                <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <a href="#" class="popover-link" data-toggle="popover" data-placement="right"
                   data-html="true"
                   title="Analytics Deployment Log"
                   data-content="@(String.Join("<br/>", Model.StatusMessages.OrderBy(msg => msg.DateAdded).Select(msg => String.Format("[{0}] {1}", msg.DateAdded, msg.Message))))">
                    Previous Deployment
                </a>
            }
        </div>
        <br />
        <br />
        <div id="progressBarContainer" style="width:280px;display:none">
            <div class="progress progress-striped active">
                <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                    <span class="sr-only"></span>
                </div>
            </div>
        </div>
        <div id="deploymentStatus">

        </div>
    }
    <hr />

    <div class="panel panel-primary analytics-chart">
        <div class="panel-heading">
            <h3 class="panel-title">Charting Analytics</h3>
        </div>
        <div class="panel-body">
            <form class="form-inline" role="form">
                <div class="form-group">
                    <label class="sr-only" for="charttype">Chart Type</label>
                    @Html.DropDownList("charttype",
                        Model.Reports.Select(report => new SelectListItem { Value = report.Report, Text = report.Description }),
                        new { @class = "form-control wide" })
                </div>
                <button type="button" id="ShowChart" class="btn btn-primary">Show</button>
            </form>
        </div>
        <div class="panel-body">
            <div id="AnalyticsChart" style="width:100%;height:600px"></div>
        </div>
    </div>
}

@section Scripts {
    @if (!ViewBag.RdfeAuthorizationFailure)
    {
        <!--[if lt IE 9]><script src="//cdn.jsdelivr.net/jqplot/1.0.8/excanvas.js"></script><![endif]-->
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.min.js"></script>
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.dateAxisRenderer.min.js"></script>
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.canvasTextRenderer.min.js"></script>
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.categoryAxisRenderer.min.js"></script>
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.highlighter.min.js"></script>
        <script src="//cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.cursor.min.js"></script>
        <script type="text/javascript">
            var statusTimer;

            $(document).ready(function () {
                enableAnalyticsControls();
                $('.enable-analytics').click(function (event) {
                    enableAnalyticsControls();
                });
                enableClusterUseControls($('.cluster-use')[0]);
                $('.cluster-use').change(function (event) {
                    enableClusterUseControls(event.target);
                });
                $("form").validate().settings.submitHandler = function (form) {
                    $("#create").attr('disabled', true);
                    $("#progressBarContainer").show();
                    $('#deploymentStatus').empty();
                    $('#deploymentStatus').css('color', 'black');

                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("CreateAnalytics")',
                        data: $(form).serialize(),
                        error: function (xhr, status, error) {
                            $("#progressBar").addClass("progress-bar-danger");
                            $('#deploymentStatus').css('color', 'red');
                            $('#deploymentStatus').append(error);
                        },
                        success: function (id) {
                            statusTimer = setInterval(function () { displayStatus(id) }, 3000);
                        }
                    });
                };
                $('.popover-link').popover({
                    placement : 'right',
                    template: '<div class="popover" style="max-width: none"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>',
                });
                $(':not(#anything)').on('click', function (e) {
                    $('.popover-link').each(function () {
                        //the 'is' for buttons that trigger popups
                        //the 'has' for icons and other elements within a button that triggers a popup
                        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                            $(this).popover('hide');
                            return;
                        }
                    });
                });

                $('#ShowChart').click(function (event) {
                    var charts = @Html.Raw(Json.Encode(Model.Reports
                        .Select(report => new {
                                                Name = report.Report,
                                                Title = report.Description,
                                                Period = String.Format("1 {0}", report.TickInterval),
                                                TickFormat = report.TickFormat,
                                                ShowLegend = report.HasMultipleSeries,
                        })
                        .ToDictionary(report => report.Name)));
                    $('#AnalyticsChart').empty();
                    var selectedChart = $('#charttype')[0].value;
                    var chartInfo = charts[selectedChart];
                    if (chartInfo != null) {
                        var ajaxRenderer = function (chart, plot, options) {
                            var ret = null;
                            $.ajax({
                                async: false,
                                url: '/api/analyticsapi/' + chart.Name,
                                dataType: "json",
                                success: function (data) {
                                    if (chart.ShowLegend) {
                                        plot.legend.labels = data.labels;
                                        ret = data.data;
                                    }
                                    else {
                                        ret = data;
                                    }
                                }
                            });
                            return ret;
                        };
                        $.jqplot('AnalyticsChart', chartInfo,
                            {
                                title: chartInfo.Title,
                                dataRenderer: ajaxRenderer,
                                axes: {
                                    xaxis: {
                                        renderer: $.jqplot.DateAxisRenderer,
                                        tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                                        tickOptions: {
                                            formatString: chartInfo.TickFormat,
                                            angle: -30
                                        },
                                        tickInterval: chartInfo.Period
                                    }
                                },
                                highlighter: {
                                    show: true,
                                    sizeAdjust: 7.5,
                                    tooltipContentEditor: function (str, seriesIndex, pointIndex, plot) {
                                        if (chartInfo.ShowLegend) {
                                            return 'Tenant: ' + plot.legend.labels[seriesIndex] + '<br>' + str;
                                        }
                                        return str;
                                    }
                                },
                                legend: {
                                    show: chartInfo.ShowLegend
                                },
                                cursor: {
                                    show: true,
                                    zoom: true
                                }
                            });
                    }
                });
            });

            function enableAnalyticsControls() {
                if ($('.enable-analytics').is(':checked')) {
                    $('.analytics-entry :input').removeAttr('disabled');
                    $('.analytics-chart :input').removeAttr('disabled');
                    $('.analytics-chart').removeClass('disabled');
                }
                else {
                    $('.analytics-entry :input').attr('disabled', true);
                    $('.analytics-chart :input').attr('disabled', true);
                    $('.analytics-chart').addClass('disabled');
                }
            }

            function enableClusterUseControls(useCluster) {
                $(".cluster-use option[value='Divider']").attr('disabled', 'disabled');
                switch (useCluster.value) {
                    case 'CreateNew':
                        $('.create-cluster').show();
                        $('.create-cluster :input').addClass("required");
                        break;

                    default:
                        $('.create-cluster').hide();
                        $('.create-cluster :input').removeClass("required");
                        break;
                }
            }

            function displayStatus(id) {
                $.ajax({
                    type: "GET",
                    url: '@Url.Action("GetAnalyticsStatus")',
                    cache: false,
                    data: { analyticsId: id },
                    error: function (xhr, status, error) {
                        $('#deploymentStatus').css('color', 'red');
                        $('#deploymentStatus').append(error);
                    },
                    success: function (data) {
                        $('#deploymentStatus').empty();
                        $.each(data, function (idx) {
                            $('#deploymentStatus').append("<div>" + data[idx].Message + "</div>");

                            if (data[idx].Success == false) {
                                $("#progressBarContainer").hide();
                                $('#deploymentStatus').css('color', 'red');
                            }
                            if (data[idx].Message.search("Finished Deployment") >= 0) {
                                $("#progressBarContainer").hide();
                                clearInterval(statusTimer);
                            }
                        });
                    }
                });
            }
        </script>
    }
}
